#!/bin/bash

echo -e "\033[4mTrafficPanel installation script.\033[0m\n"


############################################################
# BEGIN EDIT SECTION

NAMED_CONF='/etc/named.conf'
SQUID_CONF='/etc/squid/squid.conf'
SARG_CONF='/etc/sarg.conf'
SQUIDGUARD_CONF='/etc/squidguard.conf'
SQUIDGUARD_DBHOME='/var/lib/squidGuard/db'
SQUIDGUARD_LOGDIR='/var/log/squidGuard'
#SQUIDGUARD_BASES_URL='http://squidguard.mesd.k12.or.us/blacklists.tgz'

apache_user='apachetwm'
apache_group='apachetwm'

set_permissions="1"

# END EDIT SECTION
############################################################


############################################################
#	Unix system utils.
############################################################

whereis='whereis'
gawk=`which 'gawk' 2>/dev/null`
if [ ! -n "$gawk" ]; then
	echo "Installation require gawk util. Please install gawk and run configure script again."
    exit 1;
fi
grep=`$whereis 'grep'|$gawk '{print $2}'`

echo -n -e "Looking for required unix utils  .......... "
res=''
function get_tool()
{
		res=''
		util=$1

        for item in `$whereis -b $1`; do
                if [ `echo "$item" | $grep -Ec ".+/$1$"` == "1" ]; then
                        res=$item
                        break
                fi
        done;

        function print_err() {
                echo ""
                echo -e '\E[31m'"\033[1mError: \033[0m \033[1m$util\033[0m util has not been found.";
                echo "Installation aborted."
                echo -e "Please install \033[1m$util\033[0m and run TrafficPanel installation again."
                exit 1
        }

        if [ ! -n "$res" ]; then
                print_err
        elif [ -n "$res" ] && [ ! -x "$res" ]; then
                print_err
        fi
}
#	Tools used by installation script and different TrafficPanel scripts.
get_tool 'sed'; sed=$res
get_tool 'make'; make=$res
get_tool 'chown'; chown=$res
get_tool 'chgrp'; chgrp=$res
get_tool 'chmod'; chmod=$res
get_tool 'useradd'; useradd=$res
get_tool 'groupadd'; groupadd=$res
get_tool 'tar'; tar=$res
get_tool 'ifconfig'; ifconfig=$res
get_tool 'netstat'; netstat=$res
get_tool 'hostname'; hostname=$res
get_tool 'ls'; ls=$res
get_tool 'ln'; ln=$res
get_tool 'head'; head=$res
get_tool 'cat'; cat=$res
get_tool 'seq'; seq=$res
get_tool 'wc'; wc=$res
get_tool 'rm'; rm=$res
get_tool 'cp'; cp=$res
get_tool 'mkdir'; mkdir=$res
get_tool 'touch'; touch=$res
get_tool 'mv'; mv=$res
get_tool 'pwd'; pwd=$res
get_tool 'find'; find=$res
get_tool 'ps'; ps=$res
get_tool 'cut'; cut=$res
get_tool 'wget'; wget=$res

#	Tools used by different TrafficPanel scripts.
get_tool 'sha1sum'; sha1sum=$res
get_tool 'date'; date=$res
get_tool 'gzip'; gzip=$res
get_tool 'kill'; kill=$res
get_tool 'route'; route=$res
get_tool 'pppd'; pppd=$res
get_tool 'ethtool'; ethtool=$res
get_tool 'iptables'; iptables=$res
get_tool 'du'; du=$res
get_tool 'tail'; tail=$res
get_tool 'ip'; ip=$res

echo -e "[\E[32mok\033[0m]"

inst_folder=`$pwd`

###########################################################
#	Check is /etc/profile exists.
##########################################################
echo -n "Looking for '/etc/profile'   .......... "
profile_file='/etc/profile'
if [ ! -e "$profile_file" ]; then
        echo "Can not find $profile_file."
        echo "Installation aborted."
        exit 1
fi
echo -e "[\E[32mok\033[0m]"


echo -e "\nLooking for installed packages ..."
############################################################
#	Looking for bind.
############################################################
echo -n "Looking for bind   .......... "
named_bin=`$whereis named|$gawk {'print $2'}`
if [ `echo "$named_bin"|$grep -Ec ".+/named$"` != '1' ]; then
		echo -e '\E[31m'"\033[1merror:\033[0m named binary has not been found. Please install bind package manually."
		exit 1
fi
echo -e "[\E[32mok\033[0m]"

############################################################
#	Looking for squid.
############################################################
echo -n "Looking for squid   .......... "
squid_bin=`$whereis squid|$gawk {'print $2'}`
if [ `echo "$squid_bin"|$grep -Ec ".+/squid$"` != '1' ]; then
		echo -e '\E[31m'"\033[1merror:\033[0m squid binary has not been found. Please install squid package manually."
		exit 1
fi
echo -e "[\E[32mok\033[0m]"

############################################################
#	Looking for sarg.
############################################################
echo -n "Looking for sarg   .......... "
sarg_bin=`$whereis sarg|$gawk {'print $2'}`
if [ `echo "$sarg_bin"|$grep -Ec ".+/sarg$"` != '1' ]; then
		echo -e '\E[31m'"\033[1merror:\033[0m sarg binary has not been found. Please install sarg package manually."
		exit 1
fi
echo -e "[\E[32mok\033[0m]"

############################################################
#	Looking for squidGuard.
############################################################
echo -n "Looking for squidGuard   .......... "
squidGuard_bin=`$whereis squidGuard|$gawk {'print $2'}`
if [ `echo "$squidGuard_bin"|$grep -Ec ".+/squidGuard$"` != '1' ]; then
		echo -e '\E[31m'"\033[1merror:\033[0m squidGuard binary has not been found. Please install squidGuard package manually."
		exit 1
fi
echo -e "[\E[32mok\033[0m]"


############################################################
#	Looking for named.conf.
############################################################
echo -n "Looking for named config file    .......... "
readnamedConf () {
        echo "Please enter location for named.conf:"
        read NAMED_CONF
        if [ ! "$NAMED_CONF" ] || [ ! -e "$NAMED_CONF" ]; then
                echo "$NAMED_CONF file has not been found."
                readnamedConf
        fi
}
if [ ! -e "$NAMED_CONF" ]; then
	if [ -e '/etc/bind/named.conf' ]; then
		NAMED_CONF='/etc/bind/named.conf'
		echo -e "[\E[32mok\033[0m]"
	else
        echo ""
        echo -e '\E[31m'"\033[1merror:\033[0m $NAMED_CONF ['/etc/bind/named.conf'] has not been found."
        readnamedConf
	fi
else
		echo -e "[\E[32mok\033[0m]"
fi

############################################################
#	Looking for squid.conf.
############################################################
echo -n "Looking for squid config file    .......... "
readsquidConf () {
        echo "Please enter location for squid.conf:"
        read SQUID_CONF
        if [ ! "$SQUID_CONF" ] || [ ! -e "$SQUID_CONF" ]; then
			echo "$SQUID_CONF file has not been found."
			readsquidConf
        fi
}
if [ ! -e "$SQUID_CONF" ]; then
        echo ""
        echo -e '\E[31m'"\033[1merror:\033[0m $SQUID_CONF has not been found."
        readsquidConf
else
		echo -e "[\E[32mok\033[0m]"
fi

############################################################
#	Looking for sarg.conf.
############################################################
echo -n "Looking for sarg config file    .......... "
readsargConf () {
        echo "Please enter location for sarg.conf:"
        read SARG_CONF
        if [ ! "$SARG_CONF" ] || [ ! -e "$SARG_CONF" ]; then
                echo "$SARG_CONF file has not been found."
                readsargConf
        fi
}
if [ ! -e "$SARG_CONF" ]; then
	if [ -e '/etc/squid/sarg.conf' ]; then
		SARG_CONF='/etc/squid/sarg.conf'
		echo -e "[\E[32mok\033[0m]"
	else
        echo ""
        echo -e '\E[31m'"\033[1merror:\033[0m $SARG_CONF ['/etc/squid/sarg.conf'] has not been found."
        readsargConf
	fi
else
		echo -e "[\E[32mok\033[0m]"
fi

############################################################
#	Looking for squidGuard.conf.
############################################################
echo -n "Looking for squidGuard config file    .......... "
readsquidGuardConf () {
        echo "Please enter location for squidGuard.conf:"
        read SQUIDGUARD_CONF
        if [ ! "$SQUIDGUARD_CONF" ] || [ ! -e "$SQUIDGUARD_CONF" ]; then
                echo "$SQUIDGUARD_CONF file has not been found."
                readsquidGuardConf
        fi
}
if [ ! -e "$SQUIDGUARD_CONF" ]; then
	if [ -e '/etc/squid/squidGuard.conf' ]; then
		SQUIDGUARD_CONF='/etc/squid/squidGuard.conf'
		echo -e "[\E[32mok\033[0m]"
	else
        echo ""
        echo -e '\E[31m'"\033[1merror:\033[0m $SQUIDGUARD_CONF ['/etc/squid/squidGuard.conf'] has not been found."
        readsquidGuardConf
	fi
else
		echo -e "[\E[32mok\033[0m]"
fi


############################################################
#	Installing required perl modules.
############################################################

echo ""
echo -n "Looking for perl modules         .......... "

function CHECK_PERL_MODULES {

	RES=`perldoc -rlm $1|$wc -l`
	echo $RES
}

IS_XML_SIMPLE=`CHECK_PERL_MODULES 'XML::Simple'`
IS_DATE_CALC=`CHECK_PERL_MODULES 'Date::Calc'`
IS_STORABLE=`CHECK_PERL_MODULES 'Storable'`
IS_IPC_SHARELITE=`CHECK_PERL_MODULES 'IPC::ShareLite'`
IS_Authen_SASL=`CHECK_PERL_MODULES 'Authen::SASL'`

#IS_NET_SMTP_TLS=`CHECK_PERL_MODULES 'SMTP::TLS'`

if [ $IS_Authen_SASL != "1" ] || [ $IS_XML_SIMPLE != "1" ] || [ $IS_DATE_CALC != "1" ] || [ $IS_STORABLE != "1" ] || [ $IS_IPC_SHARELITE != "1" ]; then

        echo -e "\nSome required perl modules are not installed."
        echo "Do you want install them automatically using CPAN (required connection to the Internet) [y/n] ?"

	while true
	do
	    read ans
        case $ans in

                y|Y)
                        echo "Installation requires GNU C compiler."
			echo ""
                        PERL_MM_USE_DEFAULT=1
                        if [ $IS_XML_SIMPLE = "0" ]; then
                                perl -MCPAN -e 'install XML::Simple'
                        fi
                        if [ $IS_DATE_CALC = "0" ]; then
                                perl -MCPAN -e 'install Date::Calc'
                        fi
                        if [ $IS_STORABLE = "0" ]; then
                                perl -MCPAN -e 'install Storable'
                        fi
                        if [ $IS_IPC_SHARELITE = "0" ]; then
                                perl -MCPAN -e 'install IPC::ShareLite'
                        fi
			if [ $IS_Authen_SASL = "0" ]; then
				perl -MCPAN -e 'install Authen::SASL'
			fi

#                        if [ $IS_NET_SMTP_TLS = "0" ]; then
#                                perl -MCPAN -e 'install Net::SMTP::TLS'
#                        fi

                        break;;

                n|N)
                        echo "Please install following perl module(s) and run configure script again:"
                        if [ $IS_XML_SIMPLE = "0" ]; then
                                echo "XML::Simple"
                        fi
                        if [ $IS_DATE_CALC = "0" ]; then
                                echo "Date::Calc"
                        fi
                        if [ $IS_STORABLE = "0" ]; then
                                echo "Storable"
                        fi
                        if [ $IS_IPC_SHARELITE = "0" ]; then
                                echo "IPC::ShareLite"
                        fi
			if [ $IS_Authen_SASL = "0" ]; then
				echo "Authen::SASL"
			fi


#                        if [ $IS_NET_SMTP_TLS = "0" ]; then
#                                echo "Net::SMTP::TLS"
#                        fi

                        exit 1
                        break;;

                *)      echo -e "Please enter [y/n]";;
        esac
	done

fi

IS_XML_SIMPLE=`CHECK_PERL_MODULES 'XML::Simple'`
IS_DATE_CALC=`CHECK_PERL_MODULES 'Date::Calc'`
IS_STORABLE=`CHECK_PERL_MODULES 'Storable'`
IS_IPC_SHARELITE=`CHECK_PERL_MODULES 'IPC::ShareLite'`

if [ $IS_XML_SIMPLE = "0" ]; then
	echo -e "\nPlease install 'XML::Simple' and run $0 again."
	exit 1
elif [ $IS_DATE_CALC = "0" ]; then 
	echo -e "\nPlease install 'Date::Calc' and run $0 again."
	exit 1
elif [ $IS_STORABLE = "0" ]; then 
	echo -e "\nPlease install 'Storable' and run $0 again."
	exit 1
elif [ $IS_IPC_SHARELITE = "0" ]; then 
	echo -e "\nPlease install 'IPC::ShareLite' and run $0 again."
	exit 1
fi

echo -e "[\E[32mok\033[0m]"


############################################################
#	Define installation folder.
############################################################

TWM_INSTALLATION_DIR='/usr/local/twm'
echo -n -e "\nTrafficPanel folder [$TWM_INSTALLATION_DIR] : "
read ans
if [ $ans ]; then
        TWM_INSTALLATION_DIR=$ans
fi
echo "TWMFOLDER=$TWM_INSTALLATION_DIR" >> $profile_file
echo "export TWMFOLDER" >> $profile_file

source '/etc/profile'
export TWMFOLDER=$TWM_INSTALLATION_DIR

if [ ! -d "$TWMFOLDER" ]; then
        $mkdir -p $TWMFOLDER
else
		echo -e "\033[1m$TWMFOLDER\033[0m already exists.\n"
fi

############################################################
#	Define domain name.
############################################################
hname=`$hostname`
echo -n "Server name [$hname] : "
read ans
if [ $ans ]; then
        hname=$ans
fi
dname='local'
echo -n "Domain name [$dname] : "
read ans
if [ $ans ] ; then
        dname=$ans
fi
echo ""

############################################################
#	Apache installation/configuration.
############################################################
#echo -n "Do you want to use apache from TrafficPanel package? [y/n] "
#while true
#do
#        read ans
#        case $ans in
#        y|Yes)
			if [ ! -d /usr/include/asm ]; then
				echo "Please install linux-kernel-headers package from your distributive."
		                echo "Installation aborted."
                		exit 1
			fi
			echo -e "Installing apache from TrafficPanel package.\n"
			if [ `uname -i` = 'x86_64' ]; then
				./apache_setup.sh $apache_user $apache_group "$hname.$dname"
			else
				echo 'Current TrafficPanel version includes x86_64 apache version. Please install i386 apache yourself and then install TrafficPanel without apache.'
				exit
			fi
#		break;;
#
#        n|No)
#			############################################################
#			#   Looking for apache2.
#			############################################################
#			echo -n "Looking for apache2   .......... "
#			apache2_bin=`$whereis httpd2|$gawk {'print $2'}`
#			if [ `echo "$apache2_bin"|$grep -Ec ".+/httpd2$"` != '1' ]; then
#				echo -e '\E[31m'"\033[1merror:\033[0m apache2 binary has not been found. Please install apache2 package manually."
#			exit 1
#			fi
#			echo -e "[\E[32mok\033[0m]"
#
#			echo "Configuring virtual host for installed apache ..."
#            apache_user=`$cat /etc/passwd|$grep www|$gawk -F: '{print $1}'`
#            if [ ! $apache_user ]; then
#				echo  "Can not find apache user, please enter apache user name:"
#				read apache_user
#			fi
#            apache_group=`$cat /etc/group|$grep www|$gawk -F: '{print $1}'`
#            if [ ! $apache_group ]; then
#				echo "Can not find apache group, please enter apache group name:"
#				read apache_group
#			fi
#			set_permissions='1'
#			./apacheVH_setup.sh "$hname.$dname"
#			break;;
#
#        *)	echo -e "Please enter [y/n]";;
#        esac
#done

TWMlink=`$grep 'link:' /tmp/twm.installation|$gawk -F: '{print $2":"$3":"$4}'`
IP=`$grep 'ip:' /tmp/twm.installation|$gawk -F: '{print $2}'`
PORT=`$grep 'port:' /tmp/twm.installation|$gawk -F: '{print $2}'`
if [ "$PORT" = '80' ]; then
	TWMlink2="http://$IP/"
else
	TWMlink2="http://$IP:$PORT/"
fi
TWM_APACHE=`$grep 'twm_apache:' /tmp/twm.installation|$gawk -F: '{print $2}'`

$rm -Rf /tmp/twm.installation


############################################################
#	Creation templates with direct/reverse zones for named.
############################################################
echo -n "DNS modification                 .......... "
function createZoneFiles()
{
        declare -a contents

        num=`$cat ./domain_templates/$1|$wc -l`
        for ((i=1; i<=$num; i++));
        do
            contents[$i-1]=`$sed -n "${i}p; ${i}q" ./domain_templates/$1`
        done

        if [ -e "./domain_templates/$4" ];then
                $rm "./domain_templates/$4"
        fi

        for element in $($seq 0 $((${#contents[@]} - 1)))
        do
            echo "${contents[$element]}"|$gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "./domain_templates/$4"
        done
}
createZoneFiles 'TEMPLATE.ca' 'DOMAIN_NAME' "$dname" "$dname.ca"
createZoneFiles "$dname.ca" 'HOST_NAME' "$hname" "$dname.ca"
createZoneFiles "$dname.ca" 'HOST_IP' "$IP" "$dname.ca"
createZoneFiles 'TEMPLATE.lan' 'DOMAIN_NAME' "$dname" "$dname.lan"

$cp "./domain_templates/$dname.ca" ../template/kernel/
$cp "./domain_templates/$dname.lan" ../template/kernel/

echo ""
echo -n "Looking for BIND working directory    .......... "
BIND_WORKING_DIR=`$grep -v '#' $NAMED_CONF|$grep -E "directory \".+\""|$gawk -F'"' '{print $2}'`

readBinddir () {
        echo "Please enter BIND working directory :"
        read BIND_WORKING_DIR
        if [ ! "$BIND_WORKING_DIR" ] || [ ! -d "$BIND_WORKING_DIR" ]; then
                        echo "$BIND_WORKING_DIR directory has not been found."
                        readBinddir
        fi
}

if [ ! -n "$BIND_WORKING_DIR" ]; then
	echo ""
        echo -e '\E[31m'"\033[1merror:\033[0m BIND working directory has not been found."
	readBinddir
else
	echo -e "[\E[32mok\033[0m]"
fi

IS_DNAME_WRITTEN=`$grep -c "zone \"$dname\"" $NAMED_CONF`
if [ $IS_DNAME_WRITTEN = "0" ]; then
echo -e "\nzone "$dname" {
                type master;
        notify no;
                file \"$BIND_WORKING_DIR/$dname.ca\";
};

zone "1.168.192.in-addr.arpa" {
                type master;
        notify no;
                file \"$BIND_WORKING_DIR/$dname.lan\";
};" >> $NAMED_CONF
fi

$grep -v '\[direct_zone_ip_list\]' "./domain_templates/$dname.ca" > "$BIND_WORKING_DIR/$dname.ca"
$grep -v '\[reverse_zone_ip_list\]' "./domain_templates/$dname.lan" > "$BIND_WORKING_DIR/$dname.lan"

#echo -e "[\E[32mok\033[0m]"

############################################################
#	Modification squid.conf.
############################################################
echo -n "Modification SQUID config file                .......... "
IS_HOSTNAME_WRITTEN=`$grep -Ec "^visible_hostname" $SQUID_CONF`
if [ $IS_HOSTNAME_WRITTEN = "0" ]; then
	echo -e "visible_hostname $hname" >> $SQUID_CONF
fi

IS_REDIRECTOR_WRITTEN=`$grep -Ec '^(url_rewrite_program|redirect_program)' $SQUID_CONF`
if [ $IS_REDIRECTOR_WRITTEN = "0" ];then
	SQUID_VERSION=`$squid_bin -v|$grep 'Version'|$gawk '{print $4}'|$cut -d. -f1,2`
	IS_SQUID_OLD=`gawk -v OLD_SQUID_VER="2.5" -v CUR_SQUID_VER="$SQUID_VERSION" 'BEGIN { if (CUR_SQUID_VER<=OLD_SQUID_VER) {print "1"} else {print "0"} }'`

	if [ $IS_SQUID_OLD = "1" ]; then
		echo "redirect_program /usr/sbin/squidGuard -c $SQUIDGUARD_CONF" >> $SQUID_CONF
	else
		echo "url_rewrite_program /usr/sbin/squidGuard -c $SQUIDGUARD_CONF" >> $SQUID_CONF
	fi
fi
echo -e "[\E[32mok\033[0m]"

############################################################
#	Modification sarg.conf.
############################################################
echo -n "Modification SARG config file                .......... "
function changeSARGconf()
{
        declare -a contents
        num=`cat $SARG_CONF|wc -l`
        for ((i=1; i<=$num; i++));
        do
                contents[$i-1]=`sed -n "${i}p; ${i}q" $SARG_CONF`
        done

        if [ -e "$SARG_CONF" ]; then
                $rm "$SARG_CONF"
        fi

        for element in $(seq 0 $((${#contents[@]} - 1)))
        do
                echo "${contents[$element]}"|$gawk -v pattern="$1" -v replto="$2" '{gsub (pattern, replto); print}' >> "$SARG_CONF"
        done
}
changeSARGconf '^(#)?output_dir.+$' 'output_dir /srv/www/htdocs/sarg'
changeSARGconf '^(#)?resolve_ip.+$' 'resolve_ip yes'
changeSARGconf '^(#)?user_ip.+$' 'user_ip yes'
changeSARGconf '^(#)?topuser_sort_field.+$' 'topuser_sort_field BYTES reverse'
changeSARGconf '^(#)?user_sort_field.+$' 'user_sort_field BYTES reverse'
changeSARGconf '^(#)?lastlog.+$' 'lastlog 150'
changeSARGconf '^(#)?index.+$' 'index yes'
changeSARGconf '^(#)?topsites_sort_order.+$' 'topsites_sort_order BYTES D'
changeSARGconf '^(#)?replace_index.+$' 'replace_index <?php echo str_replace(".", "_", $REMOTE_ADDR); echo ".html"; ?>'
echo -e "[\E[32mok\033[0m]"

############################################################
#	Modification squidGuard.conf.
############################################################

if [ -e "$SQUIDGUARD_CONF" ]; then
	mv $SQUIDGUARD_CONF "${SQUIDGUARD_CONF}.BAK"
fi

echo -n "squidGuard databases folder [$SQUIDGUARD_DBHOME] : "
read ans
if [ "$ans" ]; then
        squidGuarddbhome=$ans
fi
if [ ! -d "$SQUIDGUARD_DBHOME" ]; then
        $mkdir -p $SQUIDGUARD_DBHOME
fi

echo -n "squidGuard log folder [$SQUIDGUARD_LOGDIR] : "
read ans
if [ "$ans" ]; then
        squidGuardlogdir=$ans
fi
if [ ! -d "$SQUIDGUARD_LOGDIR" ]; then
        $mkdir -p $SQUIDGUARD_LOGDIR
fi

echo ""

echo "dbhome $SQUIDGUARD_DBHOME
logdir $SQUIDGUARD_LOGDIR
" > $SQUIDGUARD_CONF

declare -a dblist
dblist=( $(dir "$SQUIDGUARD_DBHOME") )
for element in $($seq 0 $((${#dblist[@]} - 1)))
do
    if [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/domains" ] && [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/urls" ]; then
echo "dest ${dblist[$element]} {
    domainlist ${dblist[$element]}/domains
    urllist ${dblist[$element]}/expressions
    }" >> $SQUIDGUARD_CONF
    elif [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/domains" ]; then
echo "dest ${dblist[$element]} {
    domainlist ${dblist[$element]}/domains
}" >> $SQUIDGUARD_CONF
    elif [ -e "$SQUIDGUARD_DBHOME/${dblist[$element]}/urls" ]; then
echo "dest ${dblist[$element]} {
    urllist ${dblist[$element]}/urls
}" >> $SQUIDGUARD_CONF
    fi
done

echo "
acl {
     default {
     }
}
" >> $SQUIDGUARD_CONF


############################################################
#	Compiling squidGuard bases.
############################################################
echo "Compiling SquidGuard bases."
$squidGuard_bin -c $SQUIDGUARD_CONF -C all
echo ""
echo -e "SquidGuard bases compiled                  .......... [\E[32mok\033[0m]\n"
echo ""

if [ ! -e "/etc/squid/squidguard.conf" ]; then
	$ln -s $SQUIDGUARD_CONF "/etc/squid/squidguard.conf"
fi
#	setting appropriate permissions to squidGuard databases folder.
$chmod -R 775 $SQUIDGUARD_DBHOME
$chown -R root:$apache_group $SQUIDGUARD_DBHOME


############################################################
#	Edit and compile sources.
############################################################
echo -n "Compiling sources                  .......... "
function editCsources ()
{
        declare -a content
        num=`$cat ./src/$1/${1}.c | $wc -l`
        for ((i=1; i<=$num; i++));
        do
                content[$i-1]=`$sed -n "${i}p; ${i}q" ./src/$1/${1}.c`
        done
        if [ -e "./src/$1/${1}.c" ]; then
                $rm "./src/$1/${1}.c"
        fi
        for element in $(seq 0 $((${#content[@]} - 1)))
        do
                echo "${content[$element]}"| $gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "./src/$1/${1}.c"
        done
}

editCsources 'forker' '*twmfolder = argv\\[1\\];' "*twmfolder = \"$TWMFOLDER\";"
editCsources 'runner' '*twmfolder = "\\[TWMFOLDER\\]";' "*twmfolder = \"$TWMFOLDER\";"

cd ./src/forker/
./compile.sh $apache_group
cd ../../
cd ./src/runner/
./compile.sh $apache_group
cd ../../
echo -e "[\E[32mok\033[0m]"

############################################################
#	Modification startup scripts.
############################################################
echo -n "Modification startup scripts                .......... "
function changeInitscript()
{
         declare -a contents
         num=`$cat $1|$wc -l`
         for ((i=1; i<=$num; i++));
         do
                 contents[$i-1]=`$sed -n "${i}p; ${i}q" $1`
         done

         if [ -e "$1" ]; then
                 $rm "$1"
         fi

         for element in $($seq 0 $((${#contents[@]} - 1)))
         do
                 echo "${contents[$element]}"|$gawk -v pattern="$2" -v replto="$3" '{gsub (pattern, replto); print}' >> "$1"
         done
}

changeInitscript '../bin/twm.sh' 'TWMFOLDER=TWMFOLDER' "TWMFOLDER=$TWMFOLDER"
changeInitscript '../bin/init.sh' 'export TWMFOLDER=TWMFOLDER' "export TWMFOLDER=$TWMFOLDER"
changeInitscript '../bin/set_logs_permission.sh' 'chown wwwrun:www' "chown $apache_user:$apache_group"

echo -e "[\E[32mok\033[0m]"

############################################################
#	Copy TrafficPanel sources.
############################################################
echo -n "Copying TrafficPanel files                .......... "
$cp -R ../* $TWMFOLDER
echo -e "[\E[32mok\033[0m]"

echo -n "Setting appropriate file permissions                .......... "
if [ $set_permissions ]; then
	cd $TWMFOLDER
	$chown -R root:$apache_group ./
	$chmod 640 `$find . -type f|$grep -v 'apache/bin'`
	$chmod 750 `$find . -type d`
	$chmod 750 `$find . -name \*.sh`
	$chmod 750 `$find . -name \*.pl`
	$chmod 660 `$find . -name \*.xml`
	$chmod 660 `$find . -name \*.conf`
	$chmod 640 `$find . -name \*.pm`
	$chmod 770 $TWMFOLDER/backup
	$chmod -R g+w $TWMFOLDER/logs
	$chmod -R g+w $TWMFOLDER/etc/passwd
	$chmod 4750 ./bin/runner
	$chmod 4750 ./bin/forker
	$chown root:$apache_group "$BIND_WORKING_DIR/$dname.ca"
	$chown root:$apache_group "$BIND_WORKING_DIR/$dname.lan"
	$chmod 664 "$BIND_WORKING_DIR/$dname.ca"
	$chmod 664 "$BIND_WORKING_DIR/$dname.lan"
	$chmod 770 ./modules/shaping_cbq/cbq

# modules customization.
	$chmod 750 "$TWMFOLDER/modules/http_ip_limit/httpr_sl"
	$chmod 750 "$TWMFOLDER/modules/shaping_cbq/cbq.init"
	$chmod 750 "$TWMFOLDER/modules/if_meter/traff_meter"
	$chmod 664 $SQUID_CONF
	$chown root:$apache_group $SQUID_CONF
	$chmod 664 $SQUIDGUARD_CONF
	$chown root:$apache_group $SQUIDGUARD_CONF

	if [ ! -d '/etc/squid/delay' ]; then
		mkdir '/etc/squid/delay'
	fi

	if [ -d '/etc/squid/delay' ]; then
		$chmod 770 '/etc/squid/delay'
		$chown root:$apache_group '/etc/squid/delay'
	fi

	if [ ! -e "/sbin/tc" ]; then
		$ln -s /usr/sbin/tc /sbin/tc
	fi

fi
echo -e "[\E[32mok\033[0m]"
echo ""

############################################################
#	Modification TrafficPanel config.
############################################################
cd "$TWMFOLDER/install"

perl ./manage_config.pl dns _domain_name="$dname" _named_direct_zone="$dname.ca" _named_reverse_zone="$dname.lan" _named_zone_dir="$BIND_WORKING_DIR"

# setting correct path for each unix tool used by TrafficPanel exclude 'whereis' and 'gawk' utils.
perl ./manage_config.pl system_scripts $grep $sed $ls $sha1sum $date $gzip $tar $cat $seq $route $ps $wc $pppd $ethtool $ifconfig $hostname $iptables $named_bin $du $tail $touch $ip $mv $find $netstat $rm $cp $mkdir $kill $gawk

# setting variables containing $TWMFOLDER.
perl ./manage_config.pl common_twm _kernel_template="$TWMFOLDER/template/kernel" cgfolder="$TWMFOLDER/www/cgi-bin/" conf_backup_folder="$TWMFOLDER/backup/" scfolder="$TWMFOLDER/bin/" twmfolder="$TWMFOLDER/"

############################################################
#	Set default admin login and password.
############################################################
set_auth () {
        login='admin'
        echo -n "Please enter TrafficPanel administrator login name [$login] : "
        read ans
        if [ $ans ]; then
                login=$ans
        fi
        set_passwd () {
                echo -n -e "\033[1mPlease enter password : \033[0m" #\030
                read passwd
                if [ $passwd ]; then
						echo -n -e "\033[1mConfirm password :  \033[0m"
                        read passwd2
                        if [ $passwd2 ]; then
                                if [ $passwd = $passwd2 ]; then
                                        perl ./addLogin.pl $login $passwd
                                else
                                        echo "Passwords do not match."
                                        set_passwd
                                fi
                        else
                                echo "Password can not be empty. Please try again."
                                set_passwd
                        fi
                else
                        echo "Password can not be empty. Please try again."
                        set_passwd
                fi
        }
        set_passwd
}
set_auth
echo ""

cd $inst_folder
$rm -fR "$TWMFOLDER/install"

$ln -s "$TWMFOLDER/bin/twm.sh" '/etc/init.d/twm.sh'
if [ -d '/etc/init.d/rc3.d' ]; then
	$ln -s '/etc/init.d/twm.sh' '/etc/init.d/rc3.d/S10twm.sh'
	$ln -s '/etc/init.d/twm.sh' '/etc/init.d/rc3.d/K21twm.sh'
elif [ -d '/etc/rc3.d' ]; then
	$ln -s '/etc/init.d/twm.sh' '/etc/rc3.d/S10twm.sh'
	$ln -s '/etc/init.d/twm.sh' '/etc/rc3.d/K21twm.sh'
else
	echo "Can not find startup directory for the third runlevel. Please configure TrafficPanel startup by hand."
fi

if [ "$TWM_APACHE" = "1" ]; then
	echo -e "\nStarting TrafficPanel apache."
	$TWMFOLDER/apache/bin/apachectl start
#	$TWMFOLDER/apache/bin/httpd -f $TWMFOLDER/apache/conf/httpd.conf
else
	service apache2 restart
fi

#if [ `$ps ax|$grep -Ec '.+bin\/named'` = "1" ]; then
#	/etc/init.d/named restart
#else
#	/etc/init.d/named start
#fi


###########################################################################
# DONE
###########################################################################


echo -e "\nTrafficPanel files has been installed in \033[1m$TWMFOLDER.\033[0m"
echo -e "Use \033[4m$TWMlink\033[0m or \033[4m$TWMlink2\033[0m to get web access with your favorite browser.\n"


exit 0
